package com.ch.android.lookforkotlinv2.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import com.ch.android.baselib.BaseBindingActivity
import com.ch.android.baselib.SpUtil
import com.ch.android.baselib.SpUtil.getSessionId
import com.ch.android.baselib.SpUtil.getUserId
import com.ch.android.baselib.SpUtil.setHeadPic
import com.ch.android.baselib.SpUtil.setNickname
import com.ch.android.baselib.SpUtil.setSessionId
import com.ch.android.baselib.SpUtil.setUserId
import com.ch.android.lookforkotlinv2.R
import com.ch.android.lookforkotlinv2.databinding.ActivityUserLoginBinding
import com.ch.android.lookforkotlinv2.vm.UserLoginModel

class UserLoginActivity : BaseBindingActivity<ActivityUserLoginBinding>() {

    private val userLoginModel: UserLoginModel by lazy {
        ViewModelProvider(this)[UserLoginModel::class.java]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val hasLogin: Boolean = SpUtil.getSP().run {
            if (getUserId() != 0 && getSessionId().isNotEmpty()) {
                startActivity(Intent(this@UserLoginActivity, HomeActivity::class.java))
                finish()
                true
            } else {
                false
            }
        }
        if (hasLogin) {
            return
        }
        mBinding.model = userLoginModel
        userLoginModel.userLoginData.observe(this) {
            Toast.makeText(this, getString(R.string.login_successful), Toast.LENGTH_SHORT).show()

            SpUtil.getSP().run {
                setUserId(it.result!!.userId.toInt())
                setSessionId(it.result!!.sessionId)
                setNickname(it.result!!.nickName)
                setHeadPic(it.result!!.headPic)
            }
            startActivity(Intent(this, HomeActivity::class.java))
            finish()
        }
        userLoginModel.error.observe(this) {
            Toast.makeText(this, it.message ?: getString(R.string.login_error) , Toast.LENGTH_SHORT).show()
        }

        mBinding.btnLogin.text = "修改登录按钮名称"

    }

    override fun getLayout() = R.layout.activity_user_login
}